package cn.net.shuxing.yifu.common.service;


import cn.net.shuxing.yifu.common.bean.UserBankCard;
import cn.net.shuxing.yifu.common.mapper.UserBankCardMapper;
import cn.net.shuxing.yifu.common.util.CommonExample;
import cn.net.shuxing.yifu.common.util.HttpUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserBankCardService extends BaseService<UserBankCard, UserBankCardMapper> {

    @Autowired
    UserBankCardMapper userBankCardMapper;

    public List<UserBankCard> getsByUserId(Integer userId) {
        UserBankCard userBankCard = new UserBankCard();
        userBankCard.clearCreateTimeAndUpdateTime();
        userBankCard.setUserId(userId);
        return gets(userBankCard);
    }

    public boolean setBankCardDefault(Integer userId, Integer userBankCardId) {
        UserBankCard userBankCard = getByPrimaryKey(userBankCardId);
        if (userBankCard == null)
            return false;

        UserBankCard defaultBankCard = getDefaultBankCard(userId);
        if (defaultBankCard != null) {
            defaultBankCard.setIsDefault(0);
            update(defaultBankCard);
        }

        userBankCard.setIsDefault(1);
        update(userBankCard);
        return true;


    }

    public UserBankCard getDefaultBankCard(Integer userId) {
        CommonExample example = new CommonExample(UserBankCard.class);
        example.equals("userId", userId);
        example.equals("isDefault", 1);
        return getByExample(example);
    }

    /**
     * 实名认证
     *
     * @param userBankCard
     */
    public boolean verify(UserBankCard userBankCard) {
//        String host = "http://qyyhk.market.alicloudapi.com";
//        String path = "/clouds/verify/bankCard/element4";
//        String method = "POST";
//        String appcode = "1e93469bafdc438b9630565b35a70ff6";
//        Map<String, String> headers = new HashMap<String, String>();
//        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
//        headers.put("Authorization", "APPCODE " + appcode);
//        //根据API的要求，定义相对应的Content-Type
//        headers.put("Content-Type", "application/json; charset=UTF-8");
//        Map<String, String> querys = new HashMap<String, String>();
//        String bodys = "{\"name\":\""+userBankCard.getHolderName()+"\",\"idCard\":\""+userBankCard.getIdCardNum()+"\",\"bankCard\":\""+userBankCard.getBankCardNum()+"\",\"mobile\":\""+userBankCard.getPhoneNum()+"\"}";
////
//
//        try {
//            /**
//             * 重要提示如下:
//             * HttpUtils请从
//             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
//             * 下载
//             *
//             * 相应的依赖请参照
//             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
//             */
//            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
////            System.out.println(response.toString());
//            //获取response的body
//            String responseStr = EntityUtils.toString(response.getEntity());
//            System.out.println(responseStr);
//            JSONObject responseJson = JSON.parseObject(responseStr);
//            return responseJson.get("code").equals(0);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
        String host = "https://bank4check.market.alicloudapi.com";
        String path = "/bankcard4/verify";
        String method = "GET";
        String appcode = "1e93469bafdc438b9630565b35a70ff6";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
//        String name = null;
//        try {
//            name = new String(userBankCard.getHolderName().getBytes("ISO-8859-1"), "UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        querys.put("bankcard", userBankCard.getBankCardNum());
        querys.put("idcard", userBankCard.getIdCardNum());
        querys.put("mobile", userBankCard.getPhoneNum());
        querys.put("name", userBankCard.getHolderName());

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            System.out.println(response.toString());
            String responseStr = EntityUtils.toString(response.getEntity());
//            System.out.println(responseStr);
            JSONObject responseJson = JSON.parseObject(responseStr);
            if (responseJson != null)
                return responseJson.get("code").equals("0") || responseJson.get("code").equals(0);
            return false;
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
//HTTP/1.1 403 Forbidden [Server: Tengine, Date: Fri, 26 Apr 2019 07:46:49 GMT, Content-Type: text/plain;charset=UTF-8, Content-Length: 0, Connection: keep-alive, Access-Control-Allow-Origin: *, Access-Control-Allow-Methods: GET,POST,PUT,DELETE,HEAD,OPTIONS,PATCH, Access-Control-Allow-Headers: X-Requested-With,X-Sequence,X-Ca-Key,X-Ca-Secret,X-Ca-Version,X-Ca-Timestamp,X-Ca-Nonce,X-Ca-API-Key,X-Ca-Stage,X-Ca-Client-DeviceId,X-Ca-Client-AppId,X-Ca-Signature,X-Ca-Signature-Headers,X-Ca-Signature-Method,X-Forwarded-For,X-Ca-Date,X-Ca-Request-Mode,Authorization,Content-Type,Accept,Accept-Ranges,Cache-Control,Range,Content-MD5, Access-Control-Max-Age: 172800, X-Ca-Request-Id: BC192826-9E69-4347-A741-AFCA51329483, X-Ca-Error-Message: Quota Exhausted] org.apache.http.conn.BasicManagedEntity@3108e7ac
        return false;
    }

    /**
     * 实名认证
     *
     * @param userBankCard
     */
    public boolean verifyForBack(UserBankCard userBankCard) {
        String host = "https://bank4check.market.alicloudapi.com";
        String path = "/bankcard4/verify";
        String method = "GET";
        String appcode = "1e93469bafdc438b9630565b35a70ff6";
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        String name = null;
        try {
            name = new String(userBankCard.getHolderName().getBytes("ISO-8859-1"), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        querys.put("bankcard", userBankCard.getBankCardNum());
        querys.put("idcard", userBankCard.getIdCardNum());
        querys.put("mobile", userBankCard.getPhoneNum());
        querys.put("name", name);

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            System.out.println(response.toString());
            String responseStr = EntityUtils.toString(response.getEntity());
//            System.out.println(responseStr);
            JSONObject responseJson = JSON.parseObject(responseStr);
            if (responseJson != null)
                return responseJson.get("code").equals("0") || responseJson.get("code").equals(0);
            return false;
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
        }
//HTTP/1.1 403 Forbidden [Server: Tengine, Date: Fri, 26 Apr 2019 07:46:49 GMT, Content-Type: text/plain;charset=UTF-8, Content-Length: 0, Connection: keep-alive, Access-Control-Allow-Origin: *, Access-Control-Allow-Methods: GET,POST,PUT,DELETE,HEAD,OPTIONS,PATCH, Access-Control-Allow-Headers: X-Requested-With,X-Sequence,X-Ca-Key,X-Ca-Secret,X-Ca-Version,X-Ca-Timestamp,X-Ca-Nonce,X-Ca-API-Key,X-Ca-Stage,X-Ca-Client-DeviceId,X-Ca-Client-AppId,X-Ca-Signature,X-Ca-Signature-Headers,X-Ca-Signature-Method,X-Forwarded-For,X-Ca-Date,X-Ca-Request-Mode,Authorization,Content-Type,Accept,Accept-Ranges,Cache-Control,Range,Content-MD5, Access-Control-Max-Age: 172800, X-Ca-Request-Id: BC192826-9E69-4347-A741-AFCA51329483, X-Ca-Error-Message: Quota Exhausted] org.apache.http.conn.BasicManagedEntity@3108e7ac
        return false;
    }
    @Override
    public int insert(UserBankCard bean) {
        boolean verify = verify(bean);
        if (verify)
            return super.insert(bean);
        return 0;
    }

    public boolean updateUserBankCard(UserBankCard bean) {
        if (verify(bean)) {
            super.update(bean);
            return true;
        }
        return false;
    }

    @Override
    public int update(UserBankCard bean) {
        if (updateUserBankCard(bean)) {
            return -1;
        } else {
            return 1;
        }
    }


    public UserBankCard selectUserBankCard(Integer type, Integer userId) {
        return mapper.selectUserBankCard(type, userId);
    }

    public boolean bindable(String bankCardNum) {
        CommonExample example = new CommonExample(UserBankCard.class);
        example.equals("bankCardNum", bankCardNum);
        List<UserBankCard> userBankCards = getsByExampleWithoutComplete(example);
        if (userBankCards != null && !userBankCards.isEmpty())
            return false;
        return true;
    }

    public UserBankCard selectByUserIdAndType(Integer userId, Integer type) {
        return userBankCardMapper.selectUserBankCard(type, userId);
    }
}
